﻿using System;
using System.Collections.Generic;
using cz.uhul.DSMLv2;


namespace cz.uhul.DSMLv2.Server.Sql
{



  public static partial class LdRequestServerExtension
  {







    public static LdSearchResponse Execute(this LdSearchRequest srchReq)
    {

      LdDistinguishedName dn;

      if (!LdDistinguishedName.TryParse(srchReq.DistinguishedName, out dn))
        return new LdSearchResponse(
          LdResultCodeEnum.InvalidDNSyntax
          , "searchRequest failed"
          , "invalid DistinguishedName:" + srchReq.DistinguishedName
        );

      try
      {
        if (srchReq.Filter == null)
          throw new LdException("searchRequest missing valid filter");

        if(srchReq.Filter.Operation == null)
          throw new LdException("searchRequest missing valid filter");

        //execute operation against db
        List<Guid> tmpRes = srchReq.Filter.Operation.Execute(srchReq.DistinguishedName, srchReq.Scope, false);

        if (tmpRes.Count == 0)
          return new LdSearchResponse(LdResultCodeEnum.Success, "not found", null);

        LdSearchResultCollection sre = new LdSearchResultCollection();

        LdEntry ent;

        foreach (Guid g in tmpRes)
        {
          ent = new LdEntry();
          if (ent.Fill(srchReq.Attributes, srchReq.TypesOnly, g))
            sre.Add(ent);
        }

        return new LdSearchResponse(LdResultCodeEnum.Success, null, null)
        {
          SearchResultEntries = sre
        };

      }
      catch(Exception e)
      {
        return new LdSearchResponse(
          LdResultCodeEnum.OperationsError
          , "searchRequest failed for dn=" + srchReq.DistinguishedName
          , e.Message
        );
      }

    }



  }

}